// pages/ucenter/audit/audit.js
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 判断手机机型
    isIphoneX: 0,
    active: 0,
    // 主题名字
    themeName: '',
    // 选择商品的弹出层
    selectPopup: false,
    //相册选择的图片地址
    tempImagePath: "",
    // 首图图片
    fileList: [],
    // 富文本使用的数据
    formats: {},
    bottom: 0,
    readOnly: false,
    placeholder: '介绍一下你的详情吧，支持文字和图片...',
    // 富文本编辑生成的html片段
    contentHtml: '',
    // 团长默认收货地址
    checkedAddress: {},
    // 可团购商品列表
    productList: [],
    // 选择商品的总数
    goodsNumber: 0,
    // 已选商品ID
    checkedProductIDS: [],
    // 是否全选
    isEditCart: false,
    // 打开商品列表默认全选里面的商品
    checkedAllStatus: false,
    editCartList: [],
    isTouchMove: false,
    hasCartGoods: 0,
    // DataTime时间选择器显示与隐藏数据
    dataTimeShow: false,
    picktime:'',
    // DataTime时间选择器数据
    currentDate: new Date().getTime()+5*3600*1000,
    minDate: new Date().getTime(),
    maxDate:new Date().getTime()+30 * 24 * 3600 * 1000,

  },
  onLoad: function (options) {
    // 获取设备信息
    let phone = wx.getStorageSync('isIphoneX')
    if (phone) {
      this.setData({
        isIphoneX: 1
      })
    }
  },
  onShow: function () {
    let teamProducts = wx.getStorageSync('checkedProductIDS')
    if (teamProducts[0] !== undefined && teamProducts.length > 0) {
      this.setData({
        checkedProductIDS: teamProducts,
        goodsNumber: teamProducts.length
      })
      wx.removeStorageSync('checkedProductIDS');
    }
    let addressID = wx.getStorageSync('addressId')
    if (addressID == '' || addressID == undefined) {
      // 获取用户收货地址 显示默认那一条
      this.getUserAddress();
    } else {
      // 有addressID 获取指定的收货地址
      this.getAddressInfo(addressID)
    }

    wx.removeStorageSync('categoryId');
  },
  // 确认选择时间
  onConfirm(event) {
    let timeValue = util.formatTimeNum(new Date(event.detail) / 1000, 'Y-M-D h:m')
    this.setData({
      picktime: timeValue,
      dataTimeShow: false,
      currentDate:event.detail
    })
  },
  
  // 取消选择时间关闭弹框
  selectCancel() {
    this.setData({
      dataTimeShow: false
    })
  },
  // 控制时间选择器弹框的显示与隐藏
  showTimePopup() {
    this.setData({
      dataTimeShow: !this.data.dataTimeShow
    })
  },
  // 弹出层商品列表选择方法开始
  // 点击按钮回到主页
  toIndexPage: function () {
    wx.switchTab({
      url: '../../index/index',
    });
  },
  // 获取用户收获地址
  getUserAddress() {
    let that = this;
    let userID = wx.getStorageSync('userID')
    util.requestApi(api.getUserAddress, {
      userID: userID
    }).then(function (res) {
      if (res.code == 200) {
        that.setData({
          checkedAddress: res.content[0]
        })
      }
    })
  },
  // 根据地址ID获取选中的地址信息
  getAddressInfo(id) {
    let that = this;
    util.requestApi(api.getAddressInfo, {
      addressID: id
    }).then(function (res) {
      if (res.code == 200) {
        that.setData({
          checkedAddress: res.content
        })
      }
      wx.removeStorageSync('addressId')
    })
  },

  handleTap: function (event) { //阻止冒泡 

  },
  // 富文本的方法开始
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  // 编辑器初始化完成时触发
  onEditorReady() {
    const that = this;
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context;
    }).exec();
  },
  undo() {
    this.editorCtx.undo();
  },
  redo() {
    this.editorCtx.redo();
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset;
    if (!name) return;
    this.editorCtx.format(name, value);
  },
  // 通过 Context 方法改变编辑器内样式时触发，返回选区已设置的样式
  onStatusChange(e) {
    console.log("1")
    const formats = e.detail;
    this.setData({
      formats
    });
  },
  // 插入分割线
  insertDivider() {
    let that = this;
    that.editorCtx.insertDivider({
      success: function () {}
    });
  },
  // 清除
  clear() {
    let that = this;
    that.editorCtx.clear({
      success: function (res) {}
    });
  },
  // 移除样式
  removeFormat() {
    this.editorCtx.removeFormat();
  },
  // 插入当前日期
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    });
  },
  // 插入图片
  insertImage() {
    let that = this;
    wx.chooseImage({
      count: 1,
      success: (res) => {
        wx.uploadFile({
          url: 'https://function.duolaibei.com/admin/upload/serviceUp',
          filePath: res.tempFilePaths[0],
          name: 'image',
          formData: {
            user: 'test'
          },
          success(res) {
            var data = JSON.parse(res.data)
            // 上传完成需要更新 fileList
            that.editorCtx.insertImage({
              // 要预览的图片
              src: data.content,
              width: '100%',
              data: {
                id: 'abcd',
                role: 'god'
              },
              success: (res) => {
                wx.showToast({
                  title: '插入成功',
                  icon: 'success',
                  duration: 2000
                })
              }
            })
          }
        });
      }
    });
  },
  //选择图片
  chooseImage(e) {
    wx.chooseImage({
      sizeType: ['original', 'compressed'], //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        const images = this.data.images.concat(res.tempFilePaths);
        this.data.images = images.length <= 3 ? images : images.slice(0, 3);
      }
    })
  },

  //查看详细页面
  toDeatil() {
    this.editorCtx.getContents({
      success: (res) => {
        app.globalData.html = res.html
        wx.navigateTo({
          url: '../editor-details/editor'
        })

      },
      fail: (res) => {}
    });
  },

  // 点击跳转去选择地址界面
  toSelectAddress: function () {
    wx.navigateTo({
      url: '/pages/ucenter/address/index?type=1',
    });
  },
  // 跳转至添加地址界面
  toAddAddress: function () {
    wx.navigateTo({
      url: '/pages/ucenter/address-add/index',
    })
  },
  // 添加图片
  afterRead(event) {
    let that = this
    const {
      file
    } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: 'https://function.duolaibei.com/admin/upload/serviceUp', // 仅为示例，非真实的接口地址
      filePath: file.path,
      name: 'image',
      formData: {
        user: 'test'
      },
      success(res) {
        var data = JSON.parse(res.data)
        // 上传完成需要更新 fileList
        const {
          fileList = []
        } = that.data;
        fileList.push({
          ...file,
          url: data.content
        });
        that.setData({
          fileList
        });
      }
    });
  },
  // 删除照片
  deletePhoto(event) {
    let index = event.detail.index;
    let url = event.detail.file.url;
    let reqUrl = 'https://function.duolaibei.com/admin/upload/delServiceImg';
    let arr = [];
    // 获取自定义数组数据
    var file = this.data.fileList;
    for (var i = 0; i < file.length; i++) {
      if (i != index) {
        arr.push(file[i]);
      }
    }
    this.setData({
      fileList: arr
    })
    wx.request({
      url: reqUrl,
      data: {
        app: {
          name: url
        }
      },
      method: "POST",
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        if (res.code == 200) {
          wx.showToast({
            title: '移除成功',
            icon: 'success',
            duration: 1000
          })
        }
      }
    });
  },
  // 切换标签页
  onChange(event) {
    // wx.showToast({
    //   title: `切换到标签 ${event.detail.name}`,
    //   icon: 'none',
    // });
  },
  // 监听输入框团购主题的变化
  foundChange(event) {
    this.setData({
      themeName: event.detail
    })
  },
  // 提交创建团
  saveList() {
    let that = this;
    that.editorCtx.getContents({
      success: (res) => {
        that.setData({
          contentHtml: res.html
        })
        if (that.data.themeName == '' || that.data.themeName == undefined) {
          wx.showToast({
            title: '请输入团购主题',
            icon: 'none',
            duration: 2000
          })
          return;
        }
        if (that.data.fileList[0].url == '' || that.data.fileList[0].url == undefined) {
          wx.showToast({
            title: '请选择团购首图',
            icon: 'none',
            duration: 2000
          })
          return;
        }
        if (that.data.currentDate == '' || that.data.currentDate == undefined) {
          wx.showToast({
            title: '请选择过期时间',
            icon: 'none',
            duration: 2000
          })
          return;
        }
        if (that.data.checkedAddress.address == '' || that.data.checkedAddress.address == undefined) {
          wx.showToast({
            title: '请选择收货地址',
            icon: 'none',
            duration: 2000
          })
          return;
        }
        if (that.data.picktime == '') {
          wx.showToast({
            title: '请选择团购结束时间',
            icon: 'none',
            duration: 2000
          })
          return;
        }
        if (that.data.checkedProductIDS.length == 0) {
          wx.showToast({
            title: '请选择团购商品',
            icon: 'none',
            duration: 2000
          })
          return;
        }
        let userID = wx.getStorageSync('userID')
        util.requestApi(api.groupPurchase, {
          userID: userID,
          userAddress: that.data.checkedAddress.id,
          title: that.data.themeName,
          titleImg: that.data.fileList[0].url,
          content: that.data.contentHtml,
          status: 0,
          overTime: that.data.currentDate / 1000,
          productList: that.data.checkedProductIDS
        }).then(function (res) {
          if (res.code == 200) {
            wx.navigateBack();
            wx.showToast({
              title: '编辑成功',
              icon: 'success',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 3000
            })
          }
        })
      },
      fail: (res) => {
        wx.showToast({
          title: '编辑详情失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  // 打开选择商品的弹出层
  openPopup() {
    let id = this.data.teamOrderID
    wx.navigateTo({
      url: '../team-product/team-product?id=' + 0,
    })
  },
  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading()
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  }
})